package com.lxp.ssh2.dao.impl;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.CollectionUtils;

import com.lxp.ssh2.dao.BaseDAO;
import com.lxp.ssh2.dao.CompanyDAO;
import com.lxp.ssh2.po.Company;
import com.lxp.ssh2.vo.Page;
import com.lxp.ssh2.vo.PageRequest;

/**   
 * @Package com.jinzhiyun4j.ssh2.dao.impl
 * @Class com.jinzhiyun4j.ssh2.dao.impl.CompanyDAOImpl 
 * @Description: TODO
 * @author wuqing 
 * @date 2015年4月18日 下午3:09:22 
 * @version V1.0
 * Copyright 西安金智云起点 Corporation 2015       
 */
@Repository
public class CompanyDAOImpl extends BaseDAO implements CompanyDAO {

	/* (non-Javadoc)
	 * @see com.jinzhiyun4j.ssh2.dao.CompanyDAO#findAll()
	 */
	@Override
	public List<Company> findAll() {
		String hql="from Company";
		return super.getHibernateTemplate().find(hql);
	}

	/* (non-Javadoc)
	 * @see com.jinzhiyun4j.ssh2.dao.CompanyDAO#findByPageRequest(com.jinzhiyun4j.ssh2.vo.PageRequest)
	 */
	@Override
	public Page<Company> findByPageRequest(final PageRequest pageRequest) {
		HibernateTemplate template=super.getHibernateTemplate();
		final StringBuilder sbCondition=new StringBuilder();
		Map<String, String> condition=pageRequest.convertCondition();
		//org.springframework.util.CollectionUtils
		if(!CollectionUtils.isEmpty(condition)){
			if(condition.containsKey("c.name")){
				sbCondition.append(" and c.name like '%"+condition.get("c.name")+"%'");
			}
			if(condition.containsKey("c.principalTel")){
				sbCondition.append(" and c.principalTel like '%"+condition.get("c.principalTel")+"%'");
			}
			
		}
		@SuppressWarnings("unchecked")
		List<Company> list= (List<Company>)template.executeFind(new HibernateCallback<List<Company>>() {
			@Override
			public List<Company> doInHibernate(Session session) throws HibernateException,
					SQLException {
				
				StringBuilder hql=new StringBuilder("from Company c where 1=1"+sbCondition.toString());
				
				Query query=session.createQuery(hql.toString());
				query.setMaxResults(pageRequest.getSize());
				query.setFirstResult(pageRequest.getFirstRequest());
				return query.list();
			}
		});
		
		Page<Company> page=new Page<Company>();
		page.setData(list);
		page.setIndex(pageRequest.getIndex());
		page.setSize(pageRequest.getSize());
		String hql="select count(c) from Company c where 1=1 "+sbCondition.toString();
		Long total=(Long)template.find(hql).iterator().next();
		page.setTotal(total);
		page.setParameters(pageRequest.getCondition()); //将所有的查询参数放入到page对象中，以便生成查询字符串
		return page;
	}

}
